/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.prod;

import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.persistent.Maquina;
import dp1.titandevelop.titano.persistent.Proceso;
import dp1.titandevelop.titano.persistent.Zona;
import dp1.titandevelop.titano.service.MaquinaService;
import dp1.titandevelop.titano.service.ProcesoService;
import dp1.titandevelop.titano.service.ValidacionService;
import dp1.titandevelop.titano.service.ZonaService;
import dp1.titandevelop.titano.view.MensajeError;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Yulian
 */
public class ModulosT_PRO_ProcProdEditar extends javax.swing.JInternalFrame {
    private Proceso aux = new Proceso();
    private  List<Zona> zonas;
    private ArrayList<String> listaTiposString;
    private int maquinas;
    private int inicial;
    private List<Maquina> maqs;
    private ArrayList<Integer> idmaquinas;
    /**
     * Creates new form ModulosT_ALM_TMovNuevo
     */
    
    private void addList (List<Zona> lista){
        
        for(int i=0;i<lista.size();i++){
            this.cmbzona.addItem(lista.get(i).getDescripcion());
        }
    }
    public void RefreshTable() {
        AbstractTableModel aux = (AbstractTableModel)tblInsumos.getModel();
        aux.fireTableDataChanged();
    }
    private void inhabilitaBotones(){
        this.btnEliminar.setEnabled(false);
    }
    public void habilitaBotones(){
        this.btnEliminar.setEnabled(true);
    }
    private AbstractTableModel modeloTabla = new AbstractTableModel()  {  
        @Override
        public int getRowCount() {
            return maqs.size(); // cuantos registros (filas)
        }      
        @Override
        public int getColumnCount() {
            return 2; // cuantas columnas
        }  
        
        String [] titles = {"Maquina","Kwh"};
        
        @Override
        public String getColumnName(int col){
            return titles[col];
        }        
          
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object res=null;
            Maquina m = maqs.get(rowIndex);
            switch(columnIndex){
                case 0: res = m.getDescripcion(); break;
                case 1: res = m.getKwh(); break;
            }
            return res;
        }  
    };
     private int findIndex(Proceso a, List<Zona> lista) {
        int i = 0;
        int idTipo = a.getToZona().getIdzona();
        while (i < lista.size()) {
            if (idTipo == lista.get(i).getIdzona()) {
                break;
            }
            i++;
        }
        return (i + 1);
    }
    public ModulosT_PRO_ProcProdEditar(Proceso tm) {
        initComponents();
        ValidacionService val = new ValidacionService();
        ProcesoService serv = new ProcesoService();
        MaquinaService m = new MaquinaService();
        
        val.SNumeros(txtCant);
        val.SSoloLetra(txtDescripcion);
        ZonaService se = new ZonaService();
        zonas = se.buscar();
        addList(zonas);
        int index = findIndex(tm, zonas);
        this.cmbzona.setSelectedIndex(index);
        
        this.txtDescripcion.setText(tm.getDescripcion());
        this.txtCant.setText(tm.getCantidadmaquina().toString());
        this.maquinas = tm.getCantidadmaquina();
        this.inicial = tm.getCantidadmaquina();
        this.aux =tm;
        this.idmaquinas = new ArrayList<Integer>();
        this.maqs = new ArrayList<Maquina>();
        maqs = m.buscarIdProceso(tm.getIdproceso());
        tblInsumos.setModel(modeloTabla);
         this.btnEliminar.setEnabled(false);
        
        //this.tblMaqu.setVisible(false);
            
        this.inhabilitaBotones();
        
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtDescripcion = new javax.swing.JTextField();
        txtCant = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cmbzona = new javax.swing.JComboBox();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblInsumos = new javax.swing.JTable();
        btnEliminar = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setResizable(true);
        setTitle("Editar Proceso");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos"));

        jLabel1.setText("Descripción");

        txtCant.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCantActionPerformed(evt);
            }
        });
        txtCant.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCantKeyReleased(evt);
            }
        });

        jLabel2.setText("Cant. Maquinas");

        jLabel3.setText("Zona");

        cmbzona.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione" }));
        cmbzona.setToolTipText("");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtCant, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmbzona, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbzona, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Maquinas"));
        jPanel3.setToolTipText("");

        tblInsumos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Producto", "Precio"
            }
        ));
        tblInsumos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblInsumosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblInsumos);

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/eliminar.png"))); // NOI18N
        btnEliminar.setToolTipText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 376, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(334, 334, 334)
                        .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addComponent(btnEliminar)
                .addContainerGap())
        );

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/grabar.png"))); // NOI18N
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        btnCancelar.setToolTipText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnGuardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancelar))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(0, 10, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 26, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
       ValidacionService val = new ValidacionService();    
        Mensajes m = new Mensajes();
        if (val.esVacio(txtCant)|| val.esVacio(this.txtDescripcion)){
            JOptionPane.showInternalMessageDialog(this.getRootPane(), m.getCompletarCampos(), "Aviso", JOptionPane.WARNING_MESSAGE);

        }else{ 
              
        
            try{
            //maquinas es la cantidadque se reduce o aumenta del inicial
                ProcesoService tp = new ProcesoService();
                this.maquinas = Integer.parseInt(this.txtCant.getText());
                if (this.maquinas < this.inicial){
                    tp.editarProceso(aux.getIdproceso(),zonas.get(cmbzona.getSelectedIndex()).getIdzona(),this.txtDescripcion.getText(),this.inicial, idmaquinas);
                
                    aux.setCantidadmaquina(Integer.parseInt(this.txtCant.getText()));
                }
                else{
                    tp.editarProceso(aux.getIdproceso(),zonas.get(cmbzona.getSelectedIndex()).getIdzona(),this.txtDescripcion.getText(),this.inicial, this.maquinas);     
                    aux.setCantidadmaquina(this.maquinas);
                }
       
                 aux.setDescripcion(this.txtDescripcion.getText());
                 

            JOptionPane.showInternalMessageDialog(this.getRootPane(), m.getRegistrado(),"Mensaje",JOptionPane.INFORMATION_MESSAGE);
            ModulosT_PRO.menuProceso.RefreshTable();

            this.dispose();
            } catch(Exception e) {
                              JOptionPane.showInternalMessageDialog(this.getRootPane(),m.getError(),"Error",JOptionPane.ERROR_MESSAGE);
                      
                       }
           }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
         ModulosT_PRO.menuProceso.RefreshTable();
            this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void txtCantKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCantKeyReleased
        
    }//GEN-LAST:event_txtCantKeyReleased

    private void tblInsumosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblInsumosMouseClicked

    }//GEN-LAST:event_tblInsumosMouseClicked

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        this.maquinas = this.maquinas -1;
        int cant = Integer.parseInt(this.txtCant.getText());
        this.idmaquinas.add(maqs.get(tblInsumos.getSelectedRow()).getIdmaquina());
        this.maqs.remove(maqs.get(tblInsumos.getSelectedRow()));
        this.RefreshTable();
        if ( cant < this.maquinas){
            this.habilitaBotones();
        }else{
            this.inhabilitaBotones();
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void txtCantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCantActionPerformed
        int nuevo = Integer.parseInt(this.txtCant.getText());
        if (nuevo < this.maquinas){
            this.btnEliminar.setEnabled(true);
        }
        else{
            this.btnEliminar.setEnabled(false);
        }
    }//GEN-LAST:event_txtCantActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JComboBox cmbzona;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblInsumos;
    private javax.swing.JTextField txtCant;
    private javax.swing.JTextField txtDescripcion;
    // End of variables declaration//GEN-END:variables
}
